import '@/js/layui_exts/admin.js'

export function init() {
    layui.use(() => {
        const $ = layui.jquery, admin = layui.admin, form = layui.form, tree = layui.tree, treeTable = layui.treeTable,
            dropdown = layui.dropdown, util = layui.util, laydate = layui.laydate

        let catalogSelect, amdType;

        const clearDocEditor = () => {
            $('#sys-doc-submit').addClass('layui-hide')
            quill.setContents([])
            quill.enable(false)
        }
        const amdSysDoc = sysDoc => {
                amdType = sysDoc ? 'modify' : 'add'
                layer.open({
                    type: 1,
                    title: sysDoc ? '<i class="layui-icon-edit layui-icon"></i>&nbsp;编辑系统文档' : '<i class="layui-icon-add-circle layui-icon"></i>&nbsp;添加系统文档',
                    offset: 'l',
                    anim: 'slideRight',
                    shade: 0.3,
                    area: ['500px', '100%'],
                    shadeClose: true,
                    scrollbar: false,
                    id: 'amd-sys-doc-id',
                    content: $('#amd-sys-doc-content')
                })

                admin.arrSelect('pid', catalogSelect, undefined, undefined, '选择上级目录（不选时为根目录）')
                form.val('amd-sys-doc-form-filter', sysDoc ?? {id: '', pid: '', title: '', sort: ''})
            },
            bindTitle = () => $('[lay-table-id=doc-treetable] .layui-table-box .layui-table-header table thead tr th').on('click', () => amdSysDoc()),
            itTreeData = (o, pn) => {
                let arr = []
                arr.push({key: o.id, value: pn ? pn.title + '/' + o.title : o.title})

                if (o.children)
                    arr.push(...o.children.reduce((p, c) => {
                        p.push(...itTreeData(c, o))
                        return p
                    }, []))
                return arr
            }, generateSelectList = (data) => (catalogSelect = data.reduce((p, c) => {
                p.push(...itTreeData(c))
                return p
            }, [])),
            shareSysDoc = (sysDoc, code) => {
                layer.open({
                    type: 1,
                    title: '分享系统文档',
                    offset: 'l',
                    anim: 'slideRight',
                    shade: 0.3,
                    area: ['500px', '100%'],
                    shadeClose: true,
                    scrollbar: false,
                    id: 'share-sys-doc-id',
                    content: $('#share-sys-doc')
                })

                admin.enumRadio('state', 'sysDocState', sysDoc.state, true)
                laydate.render({
                    elem: '[name=overdue]',
                    type: 'datetime'
                })
                form.val('share-sys-doc-form-filter', {id: sysDoc.id, overdue: sysDoc.overdue ?? ''})
                $('#share-url').text(window.location.host + '/doc.html?i=' + code)
            }

        treeTable.render({
            elem: '#doc-treetable',
            url: '/api/sys/doc/tree',
            headers: {
                'Authorization': admin.getToken()
            },
            tree: {
                customName: {
                    name: 'title'
                },
                view: {
                    showIcon: false
                }
            },
            height: 'full-' + (51 + parseInt($('.layui-layout-admin .layui-body').css('padding-bottom'), 10)),
            parseData: ({code, msg, data}) => {
                let d = JSON.parse(admin.decrypt(data))
                return {
                    "code": code === 200 ? 0 : code,
                    "msg": msg,
                    "count": d.length,
                    "data": d
                }
            },
            cols: [[{field: 'id', hide: true}, {
                field: 'title',
                title: '<span style="cursor: pointer;"><i class="layui-icon-add-circle layui-icon"></i>&nbsp;目录</span>',
                templet: d => d.title + (d.state === 'pub' ? '<sup><i class="layui-icon-share layui-icon" style="color:' + (d.overdue > util.toDateString(new Date()) ? '#16b777' : '') + '"></i></sup>' : '')
            }]],
            page: false,
            done: ({data}) => {
                admin.perm()
                bindTitle()
                generateSelectList(data)
            }
        })

        treeTable.on('row(doc-treetable-filter)', o => {
            $('.layui-table-checked').each((i, oo) => $(oo).removeClass('layui-table-checked'))
            $(o.tr[0]).addClass('layui-table-checked')
            $('#sys-doc-submit').removeClass('layui-hide')
            quill.enable()

            admin.post('sys/doc/detail', {'id': o.data.id}, ({data}) => {
                quill.setContents(data.content ? JSON.parse(data.content) : [])
                dropdown.render({
                    elem: o.tr[0],
                    show: true,
                    data: [{
                        id: 'md',
                        title: '编辑'
                    }, {
                        id: 'rm',
                        title: '删除'
                    }, {
                        id: 'share',
                        title: '分享'
                    }],
                    click: (d) => {

                        switch (d.id) {
                            case 'md':
                                amdSysDoc(o.data)
                                break

                            case 'rm':
                                admin.confirm('确定删除【' + o.data.title + '】', () => admin.postM('sys/doc/remove', {id: o.data.id}, () => {
                                    treeTable.removeNode('doc-treetable', o.data.LAY_DATA_INDEX)
                                    clearDocEditor()
                                }), '删除提示')
                                break;

                            case 'share':
                                shareSysDoc(o.data, data.code)
                                break;
                        }
                    },
                    align: 'right',
                })
            })
        })

        form.on('submit(submit-amd-sys-doc-form)', ({field}) => {
            admin.postM('sys/doc/' + amdType, field, () => {
                layer.closeAll('page')
                treeTable.reload('doc-treetable')
                clearDocEditor()
            })
            return false
        })

        form.on('submit(submit-share-sys-doc)', ({field}) => {
            admin.postM('sys/doc/share', field, () => {
                layer.closeAll('page')
                treeTable.reload('doc-treetable')
                clearDocEditor()
            })
            return false
        })

        const uploadImg = v => {
                if (v) {
                    const input = document.createElement('input')
                    input.type = 'file'
                    input.accept = 'image/*'
                    input.onchange = async () => {
                        const file = input.files[0]
                        const formData = new FormData()
                        formData.append('file', file)

                        admin.upload('sys/doc/upload', formData, ({code, msg, data}) => {
                            layer.msg(msg)
                            if (code === 200) {
                                let length = quill.selection.savedRange.index
                                quill.insertEmbed(length, "image", data)
                                quill.setSelection(length + 1)
                            }
                        })
                    }
                    input.click()
                }
            },
            toolbarOptions = {
                container: [
                    ['bold', 'italic', 'underline', 'strike'],
                    ['blockquote', 'code-block'],
                    ['link', 'image', 'video', 'formula'],

                    [{'list': 'ordered'}, {'list': 'bullet'}, {'list': 'check'}],
                    [{'script': 'sub'}, {'script': 'super'}],
                    [{'indent': '-1'}, {'indent': '+1'}],
                    [{'direction': 'rtl'}],

                    [{'size': ['small', false, 'large', 'huge']}],
                    [{'header': [1, 2, 3, 4, 5, 6, false]}],

                    [{'color': []}, {'background': []}],
                    [{'font': []}],
                    [{'align': []}],

                    ['clean']
                ],
                handlers: {
                    image: v => uploadImg(v)
                }
            },
            quill = new Quill('#sys-doc-editor', {
                readOnly: true,
                modules: {
                    toolbar: toolbarOptions,
                    history: {
                        userOnly: true
                    }
                },
                placeholder: '输入系统文档内容……',
                theme: 'snow'
            });

        util.on({
            'save-content': () => admin.postM('sys/doc/update', {
                id: $('.layui-table-checked [data-field=id]').text(),
                content: JSON.stringify(quill.getContents())
            })
        })
        $('#share-url').click(e => {
            let text = $(e.target).text()
            navigator.clipboard.writeText(text).then(() => {
                layer.msg('已复制到剪切板')
            }, () => {
                const input = document.createElement('textarea')
                input.value = text
                document.body.appendChild(input)
                input.select()
                document.execCommand('copy')
                document.body.removeChild(input)

                layer.msg('已复制到剪切板')
            })
        })
    })

    return {};
}
